<template>
  <div class="img-edit-box">
    <div class="img-edit">
      <div :id="canvasId" class="canvas"></div>
      <div class="btn-group">
        <div v-for="(item, index) in toolbarMents" :key="index">
          <el-button :type="toolbarActiveIndex == index ? 'primary' : ''" size="small" :icon="item.icon"
            @click="clickHandler(index, item.name)" :title="item.label">{{ item.label != '添加批注' ? item.label : item.label+'(缺)' }}</el-button>

        </div>
        <input type="file" id="image-upload" name="image" style="display: none"
          accept="image/png, image/jpeg, image/gif,image/webp" multiple />
      </div>
    </div>
  </div>
</template>

<script>
import {
  App,
  Frame,
  Leafer,
  Rect,
  PointerEvent,
  LeaferEvent,
  Debug,
  Ellipse,
  Group,
  Box,
  Text,
  Platform,
  Polygon,
  Path,
  EditorEvent,
  DragEvent,
} from "leafer-editor";
import "@leafer-in/editor";
import "@leafer-in/text-editor";
import { Arrow } from "@leafer-in/arrow";
// import { Ruler } from "leafer-x-ruler";
import mosaicImgUrl1 from "@/assets/img/mosaic1.png";
import mosaicImgUrl2 from "@/assets/img/mosaic2.png";

export default {
  name: "ImgEdit",
  data() {
    return {
      // leafer: null
      canvasId: "",
      canvasApp: null,
      frame: null,
      isLoadCanvas: false,
      canvasState: [],
      stateIndex: -1,

      isDragging: false,
      selection: true,

      // lastPosX: false,
      // lastPosY: false
      content: "",
      fileId: "",
      imgJson: "",
      imgUrl: "",
      headId: "",
      uid: "",
      selectObj: "", //选中的元素

      selectColor: "#8282e7", //选择框颜色
      dialogColor: "#ff5e17",
      // directionVisible:false,
      direction: 1, //对话框箭头方向标识
      mosaicImgIndex: 0, //马萨克图片
      //批注形状
      dialogShape: 1,
      //标注形状
      markShape: 2,
      //标注边框颜色
      markBorderColor: "red",
      fontSize: "16",
      fontFamily: "宋体",
      fontColor: "red",
      fontWeight: "light", //1:加粗 0:不加粗

      //图片前缀域名
      domain: "http://xxx.com/files/",
      imgLoading: null,

      toolbarMents: [
        {
          name: "selectTool",
          label: "选择元素",
          icon: "el-icon-position",
        },
        // {
        //   name: "lockTool",
        //   label: "锁定图片",
        //   icon: "el-icon-lock",
        // },
        // {
        //   name: "upImageTool",
        //   label: "上传图片",
        //   icon: "iconfont icon-tupian",
        // },
        {
          name: "alignmentImageTool",
          label: "重新排版",
          icon: "iconfont icon-paiban",
        },
        {
          name: "arrowTool",
          label: "添加箭头",
          icon: "iconfont icon-jiantou",
          createdFactory(x, y) {
            return new Arrow({
              name: "arrowTool",
              x,
              y,
              toPoint: { x: 0, y: 0 },
              strokeWidth: 2,
              stroke: "#999999",
              editable: true,
            });
          },
          onMousemove(e, drawingBoard, point) {
            console.log(drawingBoard.selectedGraphics);
            drawingBoard.selectedGraphics.toPoint = {
              x: point.width,
              y: point.height,
            };
          },
        },
        {
          name: "addTextTool",
          label: "输入文字",
          notMove: true, //初始化禁止拖动
          cursor: "Text",
          icon: "iconfont icon-tianjiawenzi",
          createdFactory(x, y) {
            return new Text({
              name: "textTool",
              x: x - 5,
              width: 200,
              height: 35,
              y: y - 10,
              text: "请双击编辑内容",
              fontSize: 24,
              fill: "red",
              editable: true,
            });
          },
        },
        {
          name: "directionTool",
          label: "添加批注",
          icon: "iconfont icon-duihuakuang",
          createdFactory(x, y) {
            return new Box({
              name: "directionTool",
              x,
              y,
              width: 0,
              height: 0,
              fill: "#ccc",
              cornerRadius: 20,
              editable: true,
              strokeWidth: 2,
              stroke: 2,
              // children: [
              //   {
              //     tag: "Path",
              //     x: '50%',
              //     y: '50%',
              //     height: 10,
              //     width: 10,
              //     path: "M 100 100 L 200 100 L 150 200 Z", // 初始三角形
              //     // fill: "#3498db",
              //     stroke: "#2980b9",
              //     strokeWidth: 2,
              //     zIndex: 5,
              //   },
              //   // {
              //   //   tag: "Ellipse",
              //   //   x: -50,
              //   //   y: 70,
              //   //   width: 10,
              //   //   height: 10,
              //   //   fill: "transparent",
              //   //   stroke: "#2980b9",
              //   //   cursor: "pointer",
              //   //   zIndex: 5,
              //   // },
              // ],
            });
          },
          // onMousemove(e,drawingBoard,point){
          //   console.log(drawingBoard.selectedGraphics)
          // }
        },
        {
          name: "rectTool",
          label: "添加矩形",
          icon: "iconfont icon-zhengfangxing",
          strokeWidth: 2,
          stroke: "rgba(0, 0, 0, 1)",
          fill: "#fff",
          createdFactory(x, y) {
            return new Rect({
              name: "rectTool",
              x,
              y,
              width: 0,
              height: 0,
              strokeWidth: 2,
              stroke: 2,
              fill: "#999999",
              editable: true,
            });
          },
        },
        {
          name: "ellipseTool",
          label: "添加圆形",
          icon: "iconfont icon-yuanxing",
          strokeWidth: 2,
          stroke: "rgba(0, 0, 0, 1)",
          fill: "#fff",
          createdFactory(x, y) {
            return new Ellipse({
              name: "ellipseTool",
              x,
              y,
              width: 0,
              height: 0,
              innerRadius: 1,
              strokeWidth: 2,
              stroke: 2,
              fill: "red",
              editable: true,
            });
          },
        },
        {
          name: "mosaicTool",
          label: "添加遮挡",
          icon: "iconfont icon-masaike",
          strokeWidth: 2,
          stroke: "rgba(0, 0, 0, 1)",
          fill: "#fff",
          createdFactory(x, y) {
            return new Rect({
              name: "mosaicTool",
              className: "mosaic",
              x,
              y,
              width: 0,
              height: 0,
              fill: {
                type: "image",
                url: this.mosaicImgIndex == 1 ? mosaicImgUrl1 : mosaicImgUrl2,
              },
              editable: true,
            });
          },
        },
        {
          name: "delSelectElementTool",
          label: "删除元素",
          icon: "iconfont icon-shanchu",
        },
        {
          name: "clearAllTool",
          label: "清空画布",
          icon: "iconfont icon-qingkong",
        },
      ],
      //选中菜单的下标
      toolbarActiveIndex: 0,

      selectedGraphics: null,
    };
  },
  props: {
    // value: [Number, String],
    // dictType: String,
    // placeholder: String
    imgData: {
      type: Object,
      default: {
        content: "",
        fileId: "",
        imgJson: "",
        imgUrl: "",
        headId: "",
        uid: "",
      },
    },
  },
  watch: {
    imgData: {
      handler(newVal) {
        console.log(newVal);
        this.content = newVal.content;
        this.fileId = newVal.fileId;
        this.imgJson = newVal.imgJson;
        this.imgUrl = newVal.imgUrl;
        this.headId = newVal.headId;
        this.uid = newVal.uid;
        if (!this.canvasApp) {
          // 初始化画布
          this.canvasId = "canvas" + Math.floor(Math.random() * 1000) + 1;
          this.$nextTick(() => {
            this.getStyleAll();
            // 初始化
            this.init();
            //填充数据
            if (this.imgJson) {
              console.log(JSON.parse(this.imgJson).children);

              // 填充数据
              this.canvasApp.tree.set({
                children: JSON.parse(this.imgJson).children,
              });

              //重置 frame
              this.frame = this.canvasApp.tree.children[0];
            }
            //模拟添加对话框
            // this.addDirection();
          });
        }
      },
      immediate: true,
      deep: true,
    },
    toolbarActiveIndex(newValue) {
      console.log("newValue" + newValue);
      this.setEditorState(!newValue);
      this.setCursor();
    },
  },
  methods: {
    clickHandler(index, name) {
      this.toolbarActiveIndex = index;
      switch (name) {
        case "selectTool":
          this.selectionEl();
          break;
        case "lockTool":
          this.lockFn();
          break;
        case "upImageTool":
          this.upImage();
          this.toolbarActiveIndex = 0;
          break;
        case "alignmentImageTool":
          this.alignmentImage();
          break;
        // case 'arrowTool':
        //   this.addArrow()
        //   break;
        // case 'addTextTool':
        //   this.addText()
        //   break;
        // case 'directionTool':
        //   this.addDirection()
        //   break;
        // case 'rectTool':
        //   this.addRect()
        //   break;
        // case 'ellipseTool':
        //   this.addEllipse()
        //   break;
        // case 'mosaicTool':
        //   this.addMosaic()
        //   break;
        case "delSelectElementTool":
          this.delSelectElement();
          break;
        case "clearAllTool":
          this.clearAll();
          break;
      }
    },
    //锁定画布图片
    lockFn() {
      console.log(this.frame.children);
      this.frame.children.forEach((item) => {
        item.locked = true;
      });
    },
    setEditorState(state) {
      this.canvasApp.editor.cancel();
      this.canvasApp.editor.hittable = state;
      this.canvasApp.editor.visible = state;
    },
    setCursor() {
      const cursor =
        this.toolbarMents[this.toolbarActiveIndex].cursor || "crosshair";
      console.log(cursor);
      this.canvasApp.cursor = this.toolbarActiveIndex ? cursor : "auto";
    },
    getStyleAll() {
      //模糊遮盖形状样式
      // this.$http
      //   .get("/style/evidencematerialsstyle/1")
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg);
      //     }
      //     this.mosaicImgIndex = res.data.styleCode;
      //   })
      //   .catch(() => {});
      // //重点批注形状样式维护
      // this.$http
      //   .get("/style/evidencematerialsstyle/2")
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg);
      //     }
      //     this.dialogShape = res.data.styleCode;
      //   })
      //   .catch(() => {});
      // //重点标注形状样式维护
      // this.$http
      //   .get("/style/evidencematerialsstyle/3")
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg);
      //     }
      //     this.markShape = res.data.styleCode;
      //     this.markBorderColor = res.data.styleColour;
      //   })
      //   .catch(() => {});
      // //重点批注文字
      // this.$http
      //   .get("/style/evidencematerialsfont/7")
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg);
      //     }
      //     this.fontSize = res.data.fontSize;
      //     (this.fontFamily = res.data.fontStyleName),
      //       (this.fontColor = res.data.fontColor),
      //       (this.fontWeight = res.data.fontIsBold == 0 ? "light" : "bold"); //1:加粗 0:不加粗
      //   })
      //   .catch(() => {});
    },
    init() {
      console.log("init");
      this.canvasApp = new App({
        view: this.canvasId,
        width: 500,
        height: 350,
        type: "draw",
        hittable: true, // 打开交互事件
        // move: { dragOut: true },
        zoom: { disabled: true }, // 禁用缩放视图功能
        wheel: { preventDefault: false }, //鼠标滚轮
        editor: {
          stroke: this.selectColor,
          rotateable: false,
        },
      });
      // 默认配置，未经服务端允许的跨域图片不能渲染。
      Platform.image.crossOrigin = null;
      this.canvasApp.on(LeaferEvent.READY, function () {
        console.log("加载完成");
      });
      // 监听拖拽
      this.canvasApp.on(DragEvent.DOWN, this.mousedown);
      // 事件拖动中
      this.canvasApp.on(DragEvent.DRAG, this.mousemove);
      this.canvasApp.on(DragEvent.UP, this.mouseup);
      this.canvasApp.editor.on(EditorEvent.SELECT, (e) => {
        console.log(e);

        this.selectObj = e.value;
      });

      this.frame = new Frame({
        width: 500,
        height: 350,
      });
      this.canvasApp.tree.add(this.frame);
    },
    addDirection() {
      // var box = new Box({
      //   width: 100,
      //   height: 100,
      //   x:100,
      //   y:100,
      //   fill: '#FF4B4B',
      //   cornerRadius: 10,
      //   editable:true,
      //   zIndex: 100,
      //   resizeChildren: true,//子元素是否跟随 resize， 默认为 false。
      //   hitChildren: true,//子元素是否响应交互事件，默认为 true。
      //   children:[
      //     {
      //       tag: "Arrow",
      //       endArrow:"arrow",
      //       x: 50,
      //       y: 50,
      //       strokeWidth: 2,
      //       stroke: '#999999',
      //       editable: true,
      //       zIndex:5
      //     }
      //   ]
      // });
      // this.frame.add(box);

      // 创建对话框 Box
      const dialogBox = new Box({
        x: 200,
        y: 200,
        width: 150,
        height: 100,
        fill: "#FFFFFF",
        stroke: "#000000",
        strokeWidth: 2,
        radius: 10,
        editable: true,
      });

      // 创建箭头，作为 Box 的子级
      const arrow = new Polygon({
        sides: 3,
        x: 50,
        y: 50,
        width: 20,
        height: 100,
        strokeWidth: 2,
        stroke: "#999999",
        editable: true,
        zIndex: 5,
        rotate: 45,
      });

      // 添加指向控制功能
      // dialogBox.on('drag', (event) => {
      //   console.log(event)
      //   const { x, y } = event;  // 获取鼠标位置

      //   // 计算箭头指向角度
      //   const dialogCenterX = dialogBox.width / 2;
      //   const dialogCenterY = dialogBox.height / 2;
      //   const angle = Math.atan2(y - dialogCenterY, x - dialogCenterX) * (180 / Math.PI);

      //   arrow.rotation = angle + 90;  // 调整箭头角度，使其指向鼠标位置
      // });

      this.frame.add(dialogBox);
      // 把箭头作为 Box 的子级
      dialogBox.add(arrow);
    },
    mousedown(e) {
      this.aop(null, () => {
        const graphics = this.toolbarMents[this.toolbarActiveIndex];
        if (!graphics.createdFactory) return;
        const { x, y } = e.getPage();
        console.log(x, y);
        const graph = graphics.createdFactory(x, y);
        this.selectedGraphics = graph;
        this.frame.add(graph);
      });
    },
    mousemove(e) {
      this.aop(null, () => {
        const graphics = this.toolbarMents[this.toolbarActiveIndex];
        if (!graphics.createdFactory) return;
        if (!this.selectedGraphics) return;

        //不需要移动
        if (graphics.moveable) return;

        const { x, y } = this.selectedGraphics;
        console.log(x, y);
        if (!x || !y) return;
        const { x: offsetX, y: offsetY } = e.getPage();
        const [width, height] = [offsetX - x, offsetY - y];
        console.log(width, height);
        if (graphics.onMousemove) {
          graphics.onMousemove(e, this, { width, height });
        } else {
          const scaleX = width < 0 ? -1 : 1,
            scaleY = height < 0 ? -1 : 1;
          this.selectedGraphics.scaleX = scaleX;
          this.selectedGraphics.scaleY = scaleY;
          this.selectedGraphics.width = Math.abs(width);
          this.selectedGraphics.height = Math.abs(height);
        }
      });
    },
    mouseup(e) {
      this.toolbarActiveIndex = 0;
      this.selectedGraphics = null;
    },
    aop(beforeHandler, afterHandler) {
      beforeHandler && beforeHandler();
      if (this.toolbarActiveIndex === 0) return;
      afterHandler && afterHandler();
    },
    selectionEl() {
      console.log("11");
      this.canvasApp.cursor = "crosshair";
    },
    addText() {
      console.log(this.fontSize);
      const text = new Text({
        fill: this.fontColor,
        text: "文本",
        fontSize: this.fontSize,
        fontFamily: this.fontFamily,
        fontWeight: this.fontWeight,
        editable: true,
      });

      this.frame.add(text);
    },
    addArrow() {
      const arrow = new Arrow({
        y: 50,
        strokeWidth: 2,
        stroke: this.markBorderColor,
        editable: true,
      });

      this.frame.add(arrow);
    },
    /**
     * 对上传的图片进行排版，要求图片的高度跟画布保持一致，图片保持纵横比，每个图片居中显示，每个图片相互不折叠。
     */
    alignmentImage() {
      const canvasHeight = this.canvasApp.height;
      const canvasWidth = this.canvasApp.width; // 获取所有图片元素
      const images = this.frame.children.filter(
        (child) =>
          child.fill &&
          child.fill.type === "image" &&
          child.className != "mosaic"
      ); // 计算每个图片的新尺寸并水平排列

      let currentX = 0; // 用于跟踪当前图片的左侧位置
      let totalWidth = 0; // 用于计算所有图片的总宽度

      images.forEach((image, index) => {
        const originalWidth = image.width;
        const originalHeight = image.height; // 保持纵横比，调整图片高度与画布高度一致

        const newHeight = canvasHeight;
        const newWidth = (originalWidth / originalHeight) * newHeight; // 更新图片的尺寸和位置

        image.width = newWidth;
        image.height = newHeight;
        image.x = currentX;
        image.y = 0; // 所有图片都在画布顶部对齐 // 更新当前图片的右侧位置

        currentX += newWidth; // 累加所有图片的总宽度

        totalWidth += newWidth;
      }); // 如果所有图片的总宽度小于画布宽度，则将所有图片整体居中对齐

      if (totalWidth < canvasWidth) {
        const offsetX = (canvasWidth - totalWidth) / 2;
        images.forEach((image) => {
          image.x += offsetX;
        });
      }
      this.$message({
        message: "排版成功",
        type: "success",
      });
      this.toolbarActiveIndex = 0;
    },
    async upImage() {
      const images = this.frame.children.filter(
        (child) =>
          child.fill &&
          child.fill.type === "image" &&
          child.className != "mosaic"
      );
      if (images.length >= 3) {
        return this.$message.error("最多上传三张图片");
      }
      const imginput = document.getElementById("image-upload");
      imginput.click();
      var _this = this;
      imginput.onchange = async function (event) {
        console.log(event);
        var files = event.target.files;
        console.log(files.length);
        if (images.length + files.length > 3) {
          event.target.value = ""; //解决图片上传重复问题
          return _this.$message.error("最多上传三张图片");
        }
        // files.forEach(async (file,index) => {
        for (var i = 0; i < files.length; i++) {
          if (files[i]) {
            _this.imgLoading = _this.$loading({
              lock: true,
              text: "第" + (i + 1) + "张图片上传中",
              background: "rgba(0, 0, 0, 0.7)",
            });
            await _this.uploadFile(files[i]).then(({ data: res }) => {
              const resData = res.data;
              var imgUrl = resData.fileUrl;
              _this.addImage(imgUrl, i);
              _this.imgLoading.close();
              if (i == files.length - 1) {
                _this.$message({
                  message: "上传成功",
                  type: "success",
                });
                event.target.value = ""; //解决图片上传重复问题
              }
              // // 创建FileReader对象
              // var reader = new FileReader();
              // reader.readAsDataURL(file);
              // reader.onload = function (e) {
              //   const base64Image = e.target.result;
              //   event.target.value = "";//解决图片上传重复问题
              // };
            });
          }
          // });
        }
      };
    },

    addImage(imgUrl, imgIndex) {
      // 创建一个Image对象
      // const base64Image = e.target.result;
      const url = this.domain + imgUrl;
      // 创建一个 Image 对象
      const img = new Image();
      // img.src = base64Image;
      img.src = url;
      var _this = this;
      const images = this.frame.children.filter(
        (child) =>
          child.fill &&
          child.fill.type === "image" &&
          child.className != "mosaic"
      );
      var maxX = 30 * (imgIndex + 1);
      if (images.length > 0) {
        var xList = [];
        images.forEach((image, index) => {
          xList.push(image.x);
        });
        maxX = Math.max(...xList) + 30 * (imgIndex + 1);
      }
      console.log("add", maxX);
      img.onload = function () {
        //pc截图宽高
        let width = 1024;
        let height = 768;
        if (img.height > img.width) {
          width = 320;
          height = 768;
        }
        const rect = new Rect({
          width: width,
          height: height,
          x: maxX,
          y: 0,
          fill: {
            type: "image",
            url,
            mode: "stretch",
          },
          editable: true,
        });

        _this.frame.add(rect);

        // if(img.height > img.width){
        //   _this.$message({
        //     message: '截图上传完成后，您可以点击右侧菜单第二个按钮(排版)进行截图对齐。',
        //     type: 'warning'
        //   });
        // }
        _this.toolbarActiveIndex = 0;
      };
    },
    //选择对话框的方向
    // getDirection(directionFlag){
    //   this.directionVisible = true
    //   this.addDialogBox(directionFlag)
    // },
    // addDialogBox(direction) {
    //   this.directionVisible = false
    //   let pathData = ''
    //   //根据选择方向 获取不同的svg路径参数配置
    //   switch(direction){
    //     case 1://朝下
    //       pathData = 'd="M 0 0 L 0 0 L 150 0 L 150 60 L 150 150 L 90 150 L 75 180 L 60 150 L 0 150 Z"'
    //       break
    //     case 2://朝左
    //       pathData = 'd="M 0 0 L 0 0 L 150 0 L 150 150 L 0 150 L 0 90 L -30 75 L 0 60 Z"'
    //       break
    //     case 3://朝右
    //       pathData = 'd="M 0 0 L 0 0 L 150 0 L 150 60 L 180 75 L 150 90 L 150 150 L 0 150 Z"'
    //       break
    //     default://朝上
    //       pathData = 'd="M 0 0 L 0 0 L 60 0 L 75 -30 L 90 0 L 150 0 L 150 150 L 0 150 Z"'
    //   }
    //   const box = new Box({
    //     tag: "Pagh",
    //     path: pathData,
    //     stroke: this.markBorderColor, // 边框颜色
    //     scale: 1,
    //     // fill:this.dialogColor,
    //     height: 150,
    //     width: 150, // 多边形的实际宽度
    //     x: 50,
    //     y: 50,
    //     editable: true,
    //     textBox: true,
    //     resizeChildren: true,
    //     hitChildren: false,
    //     dashPattern: [],
    //     strokeWidth: 2,
    //     children: [
    //       {
    //         tag: "Text",
    //         text: "双击输入",
    //         fill: this.fontColor,
    //         fontSize: this.fontSize,
    //         fontFamily: this.fontFamily,
    //         fontWeight: this.fontWeight,
    //         textAlign: 'left',
    //         verticalAlign: 'top',
    //         editable: true,
    //         letterSpacing:0,
    //         lineHeight:{
    //           type: 'percent',
    //           value: 1.5, // 150%
    //         },
    //         // resizeFontSize: true,  //加了这个属性为true后Box的缩放不正常
    //         width: 160 - 20, // 文本框的宽度与多边形一致，减去左右外边距
    //         height: 150 - 20, // 文本框的初始高度与多边形一致，减去上下外边距
    //         x: 10, // 左外边距
    //         y: 10, // 上外边距
    //       },
    //     ],
    // });

    // this.frame.add(box);
    // },
    addRect() {
      const rect = new Rect({
        width: 100,
        height: 100,
        fill: "transparent",
        stroke: this.markBorderColor, // 边框
        strokeWidth: 2, // 边框粗细
        editable: true,
      });

      this.canvasApp.tree.add(rect);
    },
    addEllipse() {
      const ellipse = new Ellipse({
        width: 100,
        height: 100,
        fill: "transparent",
        stroke: this.markBorderColor, // 边框
        strokeWidth: 2, // 边框粗细
        editable: true,
      });
      this.canvasApp.tree.add(ellipse);
    },
    addMosaic() {
      const rect = new Rect({
        className: "mosaic",
        width: 100,
        height: 50,
        fill: {
          type: "image",
          url: this.mosaicImgIndex == 1 ? mosaicImgUrl1 : mosaicImgUrl2,
        },
        editable: true,
      });

      this.frame.add(rect);
    },
    delSelectElement() {
      if (Array.isArray(this.selectObj)) {
        this.selectObj.forEach((item) => {
          item.destroy();
          this.canvasApp.editor.target = null;
        });
        return "Array";
      } else if (
        this.selectObj instanceof Object &&
        !(this.selectObj instanceof Array)
      ) {
        this.selectObj.destroy(); //删除选中元素
        this.canvasApp.editor.target = null;
        return "Object";
      }
    },
    clearAll() {
      this.$confirm("确定要清空当前所有内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.canvasApp.tree.clear();
          this.canvasApp.editor.target = null;
          this.frame = new Frame({
            width: 1024,
            height: 768,
          });
          this.canvasApp.tree.add(this.frame);
        })
        .catch(() => { });
    },
    async savaImg() {
      var _this = this;
      console.log(process.env.VUE_APP_NODE_ENV);

      return new Promise(async (resolve, reject) => {
        const canvasData = await _this.canvasApp.tree.export("png", {
          blob: true,
        });
        this.uploadFile(canvasData.data).then(({ data: res }) => {
          const resData = res.data;
          console.log(resData);
          this.imgUrl = resData.fileUrl;

          const fileData = {
            fileContent: this.content ? this.content : "",
            fileId: resData.id,
            fileJson: this.canvasApp.tree.toString(),
            uid: this.uid,
          };
          this.$emit("setData", fileData);
          resolve();
        });
      });
    },
    async uploadFile(file) {
      console.log(file);
      const formData = new FormData();
      formData.append("file", file, "image.png");
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      return await this.$http.post("/file/upload", formData, config);
    },
  },
  mounted() { },
  beforeDestroy() {
    this.canvasApp.destroy();
  },
};
</script>

<style lang="scss" scoped>
.img-edit-box {
  display: flex;
  flex-direction: column;
  margin-bottom: 5px;
  border: 1px solid red;
}

.img-edit {
  // width: 1100px;
  height: 350px;
  display: flex;
  border-radius: 4px;

  .btns-box {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    border: 1px solid #dcdfe6;
  }
}

.btn-group {
  display: flex;
  flex-direction: column;
  flex: 1;
  align-items: center;
  justify-content: space-evenly;
}

.canvas {
  // border:1px solid red;
  border-right: 1px solid red;
}

.el-button+.el-button {
  margin-left: 0 !important;
}

::v-deep .el-input__inner {
  text-align: center;
}

.el-dialog {
  .el-dialog__body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }

  .button-container {
    display: flex;
    justify-content: space-between; // 使按钮均匀分布
    gap: 10px; // 按钮之间的间距
    width: 100%; // 使容器宽度占满对话框

    .el-button {
      flex: 1; // 使按钮等宽
      text-align: center; // 文本居中
    }
  }
}
</style>
